package com.javen.consumer;

import com.javen.config.Constant;
import com.javen.sender.RabbitSender;
import com.javen.vo.Order;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class DelayConsumer {
    @Autowired
    private RabbitSender sender;

    @RabbitHandler
    @RabbitListener(queues = {Constant.DELAY_PROCESS_QUEUE_NAME})
    public void delayMessageTTL(Order order, Message message, Channel channel) throws IOException {
        try {
            int count = order.getCount();
            log.info("DelayConsumer 消费者 msg:{}, message:{}, channel:{}", order, message, channel);
            // 确定被消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            // 拒绝消息并重新返回到队列
            // channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
//            if (count < 3) {
//                order.setCount(count + 1);
//                sender.delayQueuePerMessageTTL(order, (count + 1) * 60000);
//            }
            log.info("DelayConsumer receiver success");
        } catch (Exception e) {
            e.printStackTrace();
            // 处理失败，重新压入MQ
            channel.basicRecover();
        }
    }
}